package com.pinxixi.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.pinxixi.framework.domain.order.Order;
import com.pinxixi.framework.model.response.CommonCode;
import com.pinxixi.framework.model.response.QueryResponseResult;
import com.pinxixi.pay.client.OrderApiClient;
import com.pinxixi.pay.config.AlipayConfig;
import com.pinxixi.pay.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
public class PayController {

    @RequestMapping("/alipay")
    public String pay(HttpServletRequest request) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = request.getParameter("orderId");
        //付款金额，必填
        String total_amount = request.getParameter("payment");
        //订单名称，必填
        String subject = request.getParameter("subject");
        //商品描述，可空
        String body = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println(result);
        return result;
    }

    @RequestMapping("/notifyAlipay")
    public String notifyAlipay(HttpServletRequest request) throws AlipayApiException {

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            //支付宝交易号
            String trade_no = request.getParameter("trade_no");
            //付款金额
            String total_amount = request.getParameter("total_amount");

            //根据订单编号查询订单表获取订单信息

            //判断数据库中的订单金额和total_amount是否一致

            //如果一致，修改订单状态并且削减库存

            //如果不一致，说明支付结果异常，修改订单状态为异常

            return "SUCCESS";
        }else {
            return "验签失败";
        }


    }

    //@Autowired
    //private OrderApiClient orderApiClient;

    @RequestMapping("/wxpay/{id}")
    public void wxpay(@PathVariable("id") String orderId, HttpServletRequest request, HttpServletResponse response){
        //根据订单编号查询订单信息
        //QueryResponseResult queryResponseResult = orderApiClient.getOrder(orderId);
        //Order order = (Order) queryResponseResult.getEntity();
        try {
            //根据订单信息封装得到请求XML报文
            Map<String, String> params = new HashMap<String, String>();
            params.put("mch_id", Constants.MCH_ID);
            params.put("appid", Constants.APP_ID);
            params.put("notify_url", Constants.NOTIFY_URL);
            params.put("fee_type", Constants.FEE_TYPE);
            params.put("device_info", Constants.DEVICE_INFO);
            params.put("trade_type", Constants.TRADE_TYPE);
            params.put("sign_type", Constants.SIGN_TYPE);
            params.put("nonce_str", CommUtil.getNonce_str());

            params.put("out_trade_no", orderId);
            params.put("spbill_create_ip", CommUtil.getIpAddress(request));
            params.put("body", "pinxixi微信支付");
            params.put("product_id", orderId);
            params.put("total_fee", "1");
            //MD5(appid=xxxxx&body=bwie微信支付&........&密钥)---->sign
            params.put("sign", CommUtil.generateSignature(params, Constants.API_KEY, "HMACSHA256"));

            //xstream

            String requestXML = XMLUtil.mapToXml(params);
            //将XML报文发送给微信支付服务器得到返回结果(XML)
            String resultXML = HttpUtil.postData(Constants.UFDODER_URL, requestXML);
            //解析返回的XML，从中拿到code_url字符串
            Map<String, String> result = XMLUtil.doXMLParse(resultXML);
            String codeURL = result.get("code_url");
            System.out.println(codeURL);

            // 生成验证码
            //借助zxing包中的工具，将code_url转换为图片流
            //使用response将图片流返回给前端
            QRCodeUtil.createQRCode(response, codeURL);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/refreshWxpay/{id}")
    public QueryResponseResult refreshWxpay(@PathVariable("id") String orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Boolean flag = false;

        System.out.println(orderId);
        //获取需要查询的订单编号

        Map<String, String> params = new HashMap<String, String>();
        params.put("mch_id", Constants.MCH_ID);
        params.put("appid", Constants.APP_ID);
        params.put("out_trade_no", orderId);
        params.put("nonce_str", CommUtil.getNonce_str());
        params.put("sign_type", Constants.SIGN_TYPE);
        params.put("sign", CommUtil.generateSignature(params, Constants.API_KEY, "HMACSHA256"));

        String requestXML = XMLUtil.mapToXml(params);
        System.out.println(requestXML);

        String resultXML = HttpUtil.postData(Constants.CHECK_URL, requestXML);
        System.out.println(resultXML);

        Map<String, String> result = XMLUtil.doXMLParse(resultXML);

        String trade_state = result.get("trade_state");
        if(trade_state.equals("SUCCESS")) {

            //对比订单总金额和实际支付金额
            //修改订单状态
            flag = true;
        }
        System.out.println(flag);
        return new QueryResponseResult(CommonCode.SUCCESS,flag);
    }


}
